#include "sklcc_api.h"
#include "memop_flow.h"

#include "OpenDPI_demo.h"

#include <stdio.h>
#include <assert.h>
#include <malloc.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <stdarg.h>

extern u32 ipoque_detection_get_sizeof_ipoque_flow_struct(void);
extern struct osdpi_flow* get_osdpi_flow(const struct iphdr *iph,u16 ipsize);

static u32 memop_osdpi_flows_init(struct osdpi_flow* osdpi_flows,u32 flowNum)
{
	if(flowNum <= 0 || flowNum > MAX_OSDPI_FLOWS)
		return 1;
	assert(osdpi_flows != NULL);

	//Warning:flowNum may be larger than real flow number.
	//in demo version,flowNum == MAX_OSDPI_FLOWS
	u32 size_flow_struct = ipoque_detection_get_sizeof_ipoque_flow_struct();
	u32 flow_index = 0;
	for(flow_index = 0;flow_index < flowNum;flow_index++)
	{
		memset(&osdpi_flows[flow_index],0,sizeof(struct osdpi_flow));
		osdpi_flows[flow_index].ipoque_flow = calloc(1,size_flow_struct);
		assert(osdpi_flows[flow_index].ipoque_flow != NULL);
	}

	return 0;
}

extern u32 memop_osdpi_flows_free(struct osdpi_flow* osdpi_flows,u32 flowNum)
{
	assert(osdpi_flows != NULL);
	//Warning:flowNum may be larger than real flow number.
	//in demo version,flowNum == MAX_OSDPI_FLOWS
	if(flowNum <= 0 || flowNum > MAX_OSDPI_FLOWS)
		return 1;
	
	u32 flow_index = 0;
	for(flow_index = 0;flow_index < flowNum;flow_index++)
	{
		assert(osdpi_flows[flow_index].ipoque_flow != NULL);
		free(osdpi_flows[flow_index].ipoque_flow);
		osdpi_flows[flow_index].ipoque_flow = NULL;
	}	
	free(osdpi_flows);
	osdpi_flows = NULL;

	return 0;
}

extern struct osdpi_flow* memop_osdpi_flows_create(u32 flowNum)
{
	if(flowNum <= 0 || flowNum > MAX_OSDPI_FLOWS)
		return NULL;
	struct osdpi_flow *osdpi_flows = NULL;

	osdpi_flows = malloc(flowNum * sizeof(struct osdpi_flow));
	assert(osdpi_flows != NULL);

	memop_osdpi_flows_init(osdpi_flows,flowNum);
	assert(osdpi_flows != NULL);

	return osdpi_flows;
}

extern struct osdpi_flow* memop_get_osdpi_flow(const struct iphdr *iph,u16 ipsize)
{
	assert(iph != NULL);
	return get_osdpi_flow(iph,ipsize);
}
